package uno.rocc.framework.core.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import uno.rocc.common.util.Result;
import uno.rocc.framework.security.domain.RoccUnoUserDetails;
import uno.rocc.system.domain.dao.SysUser;

import javax.servlet.http.HttpServletRequest;

@RequiredArgsConstructor
public class BaseController {


    /**
     * 获取当前用户信息
     *
     * @return
     */
    public SysUser getSysUser() {
        RoccUnoUserDetails principal = (RoccUnoUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return principal.getSysUser();
    }

    /**
     * 获取当前用户ID
     *
     * @return
     */
    public Integer getSysUserId() {
        return getSysUser().getId();
    }

    /**
     * 分页
     *
     * @param <T>
     * @return
     */
    public <T> Page<T> startPage() {
        HttpServletRequest request = getRequest();
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageNum");

        int num = 1;
        int size = 10;
        if (!ObjectUtil.isEmpty(pageNum)) {
            num = Integer.parseInt(pageNum);
        }
        if (!ObjectUtil.isEmpty(pageSize)) {
            size = Integer.parseInt(pageSize);
        }
        return Page.of(num, size);
    }


    public HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        assert servletRequestAttributes != null : "未获取到请求对象";
        return servletRequestAttributes.getRequest();
    }
}
